package com.zut.test;

import com.github.pagehelper.PageInfo;
import com.zut.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/*
 * 1、编写针对user用户的查询：要求sql即能根据id进行单个用户信息的查询，也能根据多个id同时查询多个用户信息，以及根据用户名进行模糊查询，以及分页查询等等。。。。。。
 * 2、编写针对user用户的更新操作，使用动态sql，依据传递的参数实现根据用户主键id可动态的修改用户其他相关信息。。。
 * 3、添加user用户信息，根据传递的参数实现动态的添加用户信息。
 * */
public class UserTest2 {

    private SqlSessionFactory sqlSessionFactory;
   private InputStream inputStream;

    @Before
    public void init() throws Exception{
        inputStream =Resources.getResourceAsStream("mybatis-config.xml");
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

    //通过Id查询
    @Test
    public void testFindUserByIds() throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        List<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        List<User> users = sqlSession.selectList("com.zut.mapper.UserMapper.findUserByIds",ids);
        for (User user : users) {
            System.out.println( user );
        }
        sqlSession.close();
    }

    //动态模糊查询
    @Test
    public void testFindUserByName() throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
        user.setUsername("三");
        List<User> users = sqlSession.selectList("com.zut.mapper.UserMapper.findUserByName",user);
        for (User u : users) {
            System.out.println( u );
        }
        sqlSession.close();
    }
    
  	//动态更新
    @Test
    public void testUpdateUserById() throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
		user.setId(2); 
		user.setUsername("小强");
		user.setBirthday(new Date());
		user.setSex("男");
		user.setAddress("河南");
		int rows = sqlSession.update("com.zut.mapper.UserMapper.updateUserById",user);
		if(rows>0) {
			System.out.println("修改成功！");
		}
		sqlSession.commit();
        sqlSession.close();
    }
    
    //动态添加
    @Test
    public void testInsertUser() throws Exception{
        SqlSession sqlSession = sqlSessionFactory.openSession();
        User user = new User();
		user.setUsername("小强");
		user.setBirthday(new Date());
		user.setSex("男");
		user.setAddress("河南");
		int rows = sqlSession.update("com.zut.mapper.UserMapper.insertUser",user);
		if(rows>0) {
			System.out.println("添加成功！");
		}
		sqlSession.commit();
        sqlSession.close();
    }

}
